import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse  # 导入 JSONResponse

import os
import sys

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入应用模块 - 修复导入错误
from backend.app.routers import dashboard, requirements, test_cases
from backend.app.database.session import create_tables
from fastapi.exceptions import RequestValidationError  # 新增

app = FastAPI(title="AI智能测试平台 API")

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置为前端域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(dashboard.router, prefix="/api", tags=["dashboard"])
app.include_router(requirements.router, prefix="/api", tags=["requirements"])
app.include_router(test_cases.router, prefix="/api", tags=["test_cases"])

# 包含路由
app.include_router(test_cases.router)


# 在FastAPI异常处理器中添加参数校验错误处理
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    detail = {
        "errors": [{"field": err["loc"][-1], "msg": err["msg"]} for err in exc.errors()],
        "body": exc.body
    }
    return JSONResponse(
        status_code=422,
        content={"detail": detail},
    )


@app.on_event("startup")
async def startup():
    # 创建数据库表
    create_tables()


@app.get("/")
async def root():
    return {"message": "欢迎使用AI智能测试平台 API"}


if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
